//
//  AddAddressViewController.m
//  HuaLang
//
//  Created by iking on 2017/12/16.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "AddressViewController.h"
#import "AddressTableViewCell.h"
#import "AddAddressViewController.h"

@interface AddressViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation AddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = tableViewBgColor;
    [self loadBaseTitleLable:@"收货地址管理"];
    
    [self setUpUI];
}
- (void)setUpUI
{
    [self.view addSubview:self.tableView];
    
    UIButton *btn = [UIButton buttonWithTitle:@"+ 新建地址" fontSize:16 titleColor:UIColorWhite background:navBarColor cornerRadius:6];
//    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [btn setImage:UIImageNamed(@"addaddressa") forState:(UIControlStateNormal)];
//    [btn sizeToFit];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-rateHeight(50));
        make.size.mas_offset(CGSizeMake(rateWidth(600), rateHeight(100)));
    }];
    [btn addTarget:self action:@selector(addAddress) forControlEvents:(UIControlEventTouchUpInside)];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getListData];
}
- (void)getListData
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=address&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        self.addressArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            self.addressArray = [AddressModel mj_objectArrayWithKeyValuesArray:responseObject[@"Delivery_AddressList"]];
            
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
- (void)addAddress
{
    AddAddressViewController *addressVC = [[AddAddressViewController alloc] init];
    [self.navigationController pushViewController:addressVC animated:YES];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _addressArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressTableViewCell *cell = [[AddressTableViewCell alloc] init];
    if (_addressArray.count != 0) {
        AddressModel *model = _addressArray[indexPath.section];
        cell.nameLB.text = model.addressName;
        cell.phoneLB.text = model.addressPhone;
        cell.addressLB.text = [NSString stringWithFormat:@"%@%@%@%@",model.addressProvince,model.addressCity,model.addressArea,model.addressXX];
        // 默认地址
        if ([model.addressDefault intValue] == 1) {
            [cell.selectBtn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)]; // shemoren1
        }
    }
    // 默认地址
    cell.selectBtn.tag = indexPath.section;
    [cell.selectBtn addTarget:self action:@selector(setDefaultAddress:) forControlEvents:(UIControlEventTouchUpInside)];
    // 编辑
    cell.editBtn.tag = indexPath.section;
    [cell.editBtn addTarget:self action:@selector(editAction:) forControlEvents:(UIControlEventTouchUpInside)];
    // 删除
    cell.deleteBtn.tag = indexPath.section;
    [cell.deleteBtn addTarget:self action:@selector(deleteAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.selectionStyle = NO;
    return cell;
}
#pragma mark - 设置默认地址
- (void)setDefaultAddress:(UIButton *)btn
{
    if (_addressArray.count != 0) {
        AddressModel *model = _addressArray[btn.tag];
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=setdefaultaddress&companyid=%@&code=%@&timestamp=%@&addressid=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],model.addresslId] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            self.addressArray = [NSMutableArray array];
            if ([responseObject[@"status"] intValue] == 1) {
                [self getListData];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - 删除
- (void)deleteAction:(UIButton *)btn
{
    WeakSelf
    UIAlertController *alertController = [UIAlertController initWithMessage:@"是否退删除地址？" bolck:^(void) {
        if (weakSelf.addressArray.count != 0) {
            AddressModel *model = weakSelf.addressArray[btn.tag];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=deleteaddress&companyid=%@&code=%@&timestamp=%@&addressid=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],model.addresslId] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                weakSelf.addressArray = [NSMutableArray array];
                if ([responseObject[@"status"] intValue] == 1) {
                    [weakSelf getListData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
                
            }];
        }
    } cancelBolck:^(void) {
        
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 编辑
- (void)editAction:(UIButton *)btn
{
    if (_addressArray.count != 0) {
        AddressModel *model = _addressArray[btn.tag];
        AddAddressViewController *addAddressVC = [[AddAddressViewController alloc] init];
        addAddressVC.addressModel = model;
        [self.navigationController pushViewController:addAddressVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(230);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(10);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(10))];
//    bgV.backgroundColor = tableViewBgColor;
//
//    return bgV;
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.addressArray.count != 0) {
        AddressModel *model = _addressArray[indexPath.section];
        [self.delegate sendAddressModel:model];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(200)) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
